﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Collections.Generic;
using System.Linq;
using WPF_MVVM_Test.Services.Plan;
using WPF_MVVM_Test.MVVM_Model.Plan;
using System.Windows;
using WPF_MVVM_Test.MVVM_ViewModel.Plan;

namespace WPF_MVVM_Test.MVVM_ViewModel.Plan
{
    /// <summary>
    /// 生产计划ViewModel - 继承BaseViewModel，复用基础功能
    /// </summary>
    public class ProductPlanViewModel : BaseViewModel
    {
        #region 事件
        /// <summary>
        /// 请求导航到新增页面事件
        /// </summary>
        public static event Action? RequestNavigateToAddPage;
        #endregion
        #region 私有字段
        private readonly ProductPlanService _productPlanService;
        private string _message = string.Empty;
        private string _searchKeyword = string.Empty;
        private string _selectedDateType = string.Empty;
        private string _selectedProductName = string.Empty;
        private int _currentPage = 1;
        private int _pageSize = 10;
        private int _totalCount = 0;
        private int _totalPages = 0;
        private bool _isLoading = false;
        #endregion

        #region 实时监控相关字段
        private System.Timers.Timer? _refreshTimer;
        private bool _isAutoRefreshEnabled = false;
        private int _autoRefreshInterval = 30; // 默认30秒刷新一次
        private DateTime _lastRefreshTime = DateTime.Now;
        #endregion

        #region 公共属性
        /// <summary>
        /// 生产计划列表
        /// </summary>
        public ObservableCollection<ProductplanModel> ProductPlans { get; }

        /// <summary>
        /// 状态消息
        /// </summary>
        public string Message
        {
            get => _message;
            set => SetProperty(ref _message, value);
        }

        /// <summary>
        /// 搜索关键字
        /// </summary>
        public string SearchKeyword
        {
            get => _searchKeyword;
            set => SetProperty(ref _searchKeyword, value);
        }

        /// <summary>
        /// 选中的日期类型
        /// </summary>
        public string SelectedDateType
        {
            get => _selectedDateType;
            set => SetProperty(ref _selectedDateType, value);
        }

        /// <summary>
        /// 选中的产品名称
        /// </summary>
        public string SelectedProductName
        {
            get => _selectedProductName;
            set => SetProperty(ref _selectedProductName, value);
        }

        /// <summary>
        /// 当前页码
        /// </summary>
        public int CurrentPage
        {
            get => _currentPage;
            set => SetProperty(ref _currentPage, value);
        }

        /// <summary>
        /// 每页大小
        /// </summary>
        public int PageSize
        {
            get => _pageSize;
            set => SetProperty(ref _pageSize, value);
        }

        /// <summary>
        /// 总记录数
        /// </summary>
        public int TotalCount
        {
            get => _totalCount;
            set => SetProperty(ref _totalCount, value);
        }

        /// <summary>
        /// 总页数
        /// </summary>
        public int TotalPages
        {
            get => _totalPages;
            set => SetProperty(ref _totalPages, value);
        }

        /// <summary>
        /// 是否正在加载
        /// </summary>
        public bool IsLoading
        {
            get => _isLoading;
            set => SetProperty(ref _isLoading, value);
        }

        /// <summary>
        /// 分页信息显示文本
        /// </summary>
        public string PageInfo
        {
            get
            {
                if (TotalCount == 0)
                    return "暂无数据";
                
                var startIndex = (CurrentPage - 1) * PageSize + 1;
                var endIndex = Math.Min(CurrentPage * PageSize, TotalCount);
                
                return $"显示第 {startIndex}-{endIndex} 条记录，共 {TotalCount} 条";
            }
        }

        #region 分页相关属性
        /// <summary>
        /// 是否可以上一页
        /// </summary>
        public bool CanGoPreviousPage => CurrentPage > 1;

        /// <summary>
        /// 是否可以下一页
        /// </summary>
        public bool CanGoNextPage => CurrentPage < TotalPages;
        #endregion
        #endregion

        #region 搜索筛选属性
        private string? _searchPlanNumber = string.Empty;
        private string? _searchUnit = string.Empty;
        private int? _searchStatus = null;

        /// <summary>
        /// 计划编号/计划名称搜索
        /// </summary>
        public string? SearchPlanNumber
        {
            get => _searchPlanNumber;
            set => SetProperty(ref _searchPlanNumber, value);
        }

        /// <summary>
        /// 单位搜索
        /// </summary>
        public string? SearchUnit
        {
            get => _searchUnit;
            set => SetProperty(ref _searchUnit, value);
        }

        /// <summary>
        /// 状态搜索
        /// </summary>
        public int? SearchStatus
        {
            get => _searchStatus;
            set => SetProperty(ref _searchStatus, value);
        }

        /// <summary>
        /// 状态选项列表 - 用于下拉框绑定
        /// </summary>
        public List<StatusOption> StatusOptions { get; } = new List<StatusOption>
        {
            new StatusOption { Value = null, Text = "全部状态" },
            new StatusOption { Value = 0, Text = "未分解" },
            new StatusOption { Value = 1, Text = "已分解" },
            new StatusOption { Value = 2, Text = "已完成" },
            new StatusOption { Value = 3, Text = "已关闭" },
            new StatusOption { Value = 4, Text = "已撤回" },
            new StatusOption { Value = 5, Text = "进行中" }
        };
        #endregion

        #region 实时监控属性
        /// <summary>
        /// 是否启用自动刷新
        /// </summary>
        public bool IsAutoRefreshEnabled
        {
            get => _isAutoRefreshEnabled;
            set
            {
                _isAutoRefreshEnabled = value;
                OnPropertyChanged();
                
                if (value)
                    StartAutoRefresh();
                else
                    StopAutoRefresh();
            }
        }

        /// <summary>
        /// 自动刷新间隔（秒）
        /// </summary>
        public int AutoRefreshInterval
        {
            get => _autoRefreshInterval;
            set
            {
                _autoRefreshInterval = Math.Max(5, value); // 最小5秒
                OnPropertyChanged();
                
                if (IsAutoRefreshEnabled)
                {
                    StopAutoRefresh();
                    StartAutoRefresh();
                }
            }
        }

        /// <summary>
        /// 最后刷新时间
        /// </summary>
        public DateTime LastRefreshTime
        {
            get => _lastRefreshTime;
            set
            {
                _lastRefreshTime = value;
                OnPropertyChanged();
                OnPropertyChanged(nameof(LastRefreshTimeText));
            }
        }

        /// <summary>
        /// 最后刷新时间文本
        /// </summary>
        public string LastRefreshTimeText => $"最后更新: {LastRefreshTime:HH:mm:ss}";

        /// <summary>
        /// 自动刷新状态文本
        /// </summary>
        public string AutoRefreshStatusText => IsAutoRefreshEnabled 
            ? $"🔄 自动刷新中 ({AutoRefreshInterval}秒)" 
            : "⏸️ 已暂停自动刷新";
        #endregion

        #region 命令
        public ICommand RefreshCommand { get; }
        public ICommand SearchCommand { get; }
        public ICommand ExportCommand { get; }
        public ICommand AddProductPlanCommand { get; }
        public ICommand EditCommand { get; }
        public ICommand DecomposeCommand { get; }
        public ICommand FirstPageCommand { get; }
        public ICommand PreviousPageCommand { get; }
        public ICommand NextPageCommand { get; }
        public ICommand LastPageCommand { get; }
        public ICommand ToggleAutoRefreshCommand { get; }
        public ICommand ClearSearchCommand { get; }
        #endregion

        #region 构造函数
        public ProductPlanViewModel()
        {
            ProductPlans = new ObservableCollection<ProductplanModel>();
            _productPlanService = new ProductPlanService();

            // 初始化命令 - 修复异步调用方式
            RefreshCommand = CreateCommand(() => _ = LoadProductPlansAsync());
            SearchCommand = CreateCommand(() => _ = SearchProductPlansAsync());
            ClearSearchCommand = CreateCommand(() => _ = ClearSearchAsync());
            AddProductPlanCommand = CreateCommand(NavigateToAddPage);
            EditCommand = CreateCommand<ProductplanModel>(EditProductPlan);
            DecomposeCommand = CreateCommand<ProductplanModel>(DecomposeProductPlan);
            ExportCommand = CreateCommand(ExportProductPlans);

            // 分页命令 - 保持原有逻辑
            FirstPageCommand = CreateCommand(() => _ = GoToPageAsync(1), () => CanGoPreviousPage);
            PreviousPageCommand = CreateCommand(() => _ = GoToPageAsync(CurrentPage - 1), () => CanGoPreviousPage);
            NextPageCommand = CreateCommand(() => _ = GoToPageAsync(CurrentPage + 1), () => CanGoNextPage);
            LastPageCommand = CreateCommand(() => _ = GoToPageAsync(TotalPages), () => CanGoNextPage);

            // 实时监控命令
            ToggleAutoRefreshCommand = CreateCommand(ToggleAutoRefresh);

            // 启动时自动加载数据
            _ = LoadProductPlansAsync();
        }
        #endregion

        #region 实时监控方法
        /// <summary>
        /// 启动自动刷新
        /// </summary>
        private void StartAutoRefresh()
        {
            StopAutoRefresh(); // 先停止现有的定时器

            _refreshTimer = new System.Timers.Timer(AutoRefreshInterval * 1000);
            _refreshTimer.Elapsed += async (sender, e) =>
            {
                try
                {
                    // 在UI线程中执行刷新
                    await System.Windows.Application.Current.Dispatcher.InvokeAsync(async () =>
                    {
                        if (!IsLoading) // 避免重复加载
                        {
                            await LoadProductPlansAsync();
                        }
                    });
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"自动刷新异常: {ex.Message}");
                }
            };
            
            _refreshTimer.AutoReset = true;
            _refreshTimer.Enabled = true;
            _refreshTimer.Start();

            OnPropertyChanged(nameof(AutoRefreshStatusText));
            System.Diagnostics.Debug.WriteLine($"🔄 启动自动刷新，间隔 {AutoRefreshInterval} 秒");
        }

        /// <summary>
        /// 停止自动刷新
        /// </summary>
        private void StopAutoRefresh()
        {
            if (_refreshTimer != null)
            {
                _refreshTimer.Stop();
                _refreshTimer.Dispose();
                _refreshTimer = null;
                OnPropertyChanged(nameof(AutoRefreshStatusText));
                System.Diagnostics.Debug.WriteLine("⏸️ 停止自动刷新");
            }
        }

        /// <summary>
        /// 切换自动刷新状态
        /// </summary>
        private void ToggleAutoRefresh()
        {
            IsAutoRefreshEnabled = !IsAutoRefreshEnabled;
        }
        #endregion

        #region 数据加载方法
        /// <summary>
        /// 加载生产计划列表 - 使用搜索参数
        /// </summary>
        private async Task LoadProductPlansAsync()
        {
            try
            {
                IsLoading = true;
                Message = "正在加载生产计划列表...";

                // 使用搜索参数调用API
                var (plans, totalCount, totalPages) = await _productPlanService.GetProductPlansAsync(
                    SearchPlanNumber,  // 计划编号/计划名称
                    SearchUnit,        // 单位
                    SearchStatus,      // 状态
                    CurrentPage,
                    PageSize);

                ProductPlans.Clear();
                foreach (var plan in plans)
                {
                    ProductPlans.Add(plan);
                }

                TotalCount = totalCount;
                TotalPages = totalPages;
                
                // 通知分页相关属性更新
                OnPropertyChanged(nameof(PageInfo));
                OnPropertyChanged(nameof(CanGoPreviousPage));
                OnPropertyChanged(nameof(CanGoNextPage));
                
                // 刷新命令状态
                CommandManager.InvalidateRequerySuggested();

                // 显示搜索结果信息
                var searchInfo = GetSearchInfo();
                Message = $"✅ 成功加载 {plans.Count} 条记录{searchInfo}";
                LastRefreshTime = DateTime.Now;
            }
            catch (Exception ex)
            {
                Message = $"❌ 加载失败: {ex.Message}";
                System.Diagnostics.Debug.WriteLine($"加载生产计划异常: {ex}");
            }
            finally
            {
                IsLoading = false;
            }
        }

        /// <summary>
        /// 搜索生产计划 - 重置到第一页并加载数据
        /// </summary>
        private async Task SearchProductPlansAsync()
        {
            // 搜索时暂时停止自动刷新
            bool wasAutoRefreshEnabled = IsAutoRefreshEnabled;
            if (IsAutoRefreshEnabled)
            {
                StopAutoRefresh();
            }

            CurrentPage = 1; // 搜索时重置到第一页
            await LoadProductPlansAsync();

            // 搜索完成后恢复自动刷新
            if (wasAutoRefreshEnabled)
            {
                IsAutoRefreshEnabled = true;
            }
        }
        #endregion

        #region 私有方法
        /// <summary>
        /// 跳转到指定页
        /// </summary>
        private async Task GoToPageAsync(int pageNumber)
        {
            if (pageNumber >= 1 && pageNumber <= TotalPages && pageNumber != CurrentPage)
            {
                CurrentPage = pageNumber;
                await LoadProductPlansAsync();
            }
        }

        /// <summary>
        /// 清空搜索条件
        /// </summary>
        private async Task ClearSearchAsync()
        {
            SearchPlanNumber = string.Empty;
            SearchUnit = string.Empty;
            SearchStatus = null;
            
            CurrentPage = 1;
            await LoadProductPlansAsync();
        }

        /// <summary>
        /// 获取搜索信息描述
        /// </summary>
        private string GetSearchInfo()
        {
            var searchConditions = new List<string>();
            
            if (!string.IsNullOrWhiteSpace(SearchPlanNumber))
                searchConditions.Add($"计划编号/名称: {SearchPlanNumber}");
            
            if (!string.IsNullOrWhiteSpace(SearchUnit))
                searchConditions.Add($"单位: {SearchUnit}");
            
            if (SearchStatus.HasValue)
            {
                var statusText = StatusOptions.FirstOrDefault(s => s.Value == SearchStatus)?.Text ?? "未知";
                searchConditions.Add($"状态: {statusText}");
            }
            
            return searchConditions.Count > 0 ? $" (筛选条件: {string.Join(", ", searchConditions)})" : "";
        }

        /// <summary>
        /// 导出生产计划
        /// </summary>
        private void ExportProductPlans()
        {
            Message = "导出功能开发中...";
        }

        /// <summary>
        /// 导航到新增页面
        /// </summary>
        private void NavigateToAddPage()
        {
            RequestNavigateToAddPage?.Invoke();
        }

        /// <summary>
        /// 编辑生产计划
        /// </summary>
        private void EditProductPlan(ProductplanModel plan)
        {
            if (plan != null)
            {
                try
                {
                    // 创建编辑弹框
                    var dialog = new WPF_MVVM_Test.MVVM_View.Dialog.EditProductPlanDialog();
                    
                    // 设置父窗口
                    if (Application.Current.MainWindow != null)
                    {
                        dialog.Owner = Application.Current.MainWindow;
                    }
                    
                    // 初始化编辑数据
                    if (dialog.DataContext is AddProductPlanViewModel viewModel)
                    {
                        viewModel.InitializeEditData(plan);
                    }
                    
                    // 显示弹框
                    if (dialog.ShowDialog() == true)
                    {
                        // 编辑成功，刷新列表
                        _ = LoadProductPlansAsync();
                        Message = $"计划 {plan.PlanName} 更新成功！";
                    }
                }
                catch (Exception ex)
                {
                    Message = $"编辑计划时发生错误: {ex.Message}";
                }
            }
        }

        /// <summary>
        /// 分解生产计划
        /// </summary>
        private async void DecomposeProductPlan(ProductplanModel plan)
        {
            if (plan != null)
            {
                try
                {
                    // 检查计划状态，只有未分解的计划才能进行分解
                    if (plan.Status != 0)
                    {
                        MessageBox.Show($"该计划状态为\"{plan.StatusText}\"，无法进行分解操作！\n只有\"未分解\"状态的计划才能进行分解。", 
                            "状态检查", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }

                    // 确认分解操作
                    var result = MessageBox.Show($"确定要分解生产计划\"{plan.PlanName}\"吗？\n\n分解后计划状态将变为\"已分解\"，此操作不可撤销。", 
                        "确认分解", MessageBoxButton.YesNo, MessageBoxImage.Question);

                    if (result == MessageBoxResult.Yes)
                    {
                        // 显示加载状态
                        Message = $"正在分解计划: {plan.PlanName}...";

                        // 调用分解API
                        var success = await _productPlanService.DecomposeProductPlanAsync(plan.Id);

                        if (success)
                        {
                            // 分解成功，刷新列表
                            await LoadProductPlansAsync();
                            Message = $"✅ 计划\"{plan.PlanName}\"分解成功！";
                        }
                        else
                        {
                            Message = $"❌ 计划\"{plan.PlanName}\"分解失败，请重试！";
                        }
                    }
                }
                catch (Exception ex)
                {
                    Message = $"❌ 分解计划时发生错误: {ex.Message}";
                    System.Diagnostics.Debug.WriteLine($"分解生产计划异常: {ex}");
                }
            }
        }
        #endregion
    }
}

/// <summary>
/// 状态选项类 - 用于下拉框
/// </summary>
public class StatusOption
{
    public int? Value { get; set; }
    public string Text { get; set; } = string.Empty;
}
